package com.qf.electronic.mall.sms.service.handler;


import com.qf.constant.RabbitConstant;
import com.qf.constant.RedisConstant;
import com.qf.util.StringUtil;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SMSHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = RabbitConstant.SMS_SEND_QUEUE)
    public void process(String phone){
        //初始化clnt,使用单例方式
        YunpianClient clnt = new
                YunpianClient("ec25476854026e1867ea17123f335888").init();

        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        //收信人
        param.put(YunpianClient.MOBILE, phone);
        String validateCode=String.valueOf((int)(Math.random()*9+1)*100000);
        param.put(YunpianClient.TEXT, "【赵伟风】您的验证码是"+validateCode+"。如非本人操作，请忽略本短信");
        Result<SmsSingleSend> r = clnt.sms().single_send(param);

        Integer code = r.getCode();
        //组织键值对,存入到Redis中
        String redisKey = StringUtil.getRedisKey(RedisConstant.REGISTER_PHONE, phone);
        //设置键值对和有效期
        redisTemplate.opsForValue().set(redisKey,code,1, TimeUnit.MINUTES);
        System.out.println("code = " + code);
        String msg = r.getMsg();
        System.out.println("msg = " + msg);
        String detail = r.getDetail();
        System.out.println("detail = " + detail);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()

        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*

        //释放clnt
        clnt.close();
    }
}
